var oframe = undefined; // 控件
var isOpened = false; // 状态
var U = 'my_name'; // 自定义用户名
var fileA; // 对比的fileA文件
var id = getQueryVariable('id'); // 当前文件
var rootPath = location.protocol + '//' + location.host + location.pathname.substring(0, location.pathname.lastIndexOf('/'));
// 绑定
$(function () {
    oframe = document.getElementById("oframe");
    // 保存按钮
    $('#save').on('click', function () {
        if (oframe.HttpInit()) {
            oframe.HttpAddPostString("id", id);
            oframe.HttpAddPostCurrFile("file", "");
            var savedId = oframe.HttpPost(rootPath + '/upload');
            alert(savedId);
        }
    });
    // 发送按钮
    $('#send').on('click', function () {
        if (oframe.HttpInit()) {
            oframe.HttpAddPostString("id", id);
            oframe.HttpAddPostCurrFile("file", "");
            var savedId = oframe.HttpPost(rootPath + '/uploadAndSend');
            alert(savedId);
            if (savedId) {
                $.post('/send', {id: savedId, to: '他的名字'}, function (data) {
                    console.log(data);
                });
            }
        }
    });
    // 历史版本
    $(document).on('click', '#history-file ul li', function () {
        if (!$(this).hasClass('selected')) {
            $(this).addClass('selected').siblings().removeClass('selected');
        }
        fileA = $(this).data('id');
        return false;
    });
    // 打开对比
    $('#compareStart').on('click', function () {
        // 从后台获取当前文件的修订版本
        $.get('/versions/' + id, function (data) {
            $('.history-file ul').empty();
            for (var i = 0; i < data.length; i++) {
                $('.history-file ul').append(
                    '<li data-id="' + data[i].md5 + '">\n' +
                    '<p class="name">' + data[i].name + '</p>\n' +
                    '<p class="time">修订方：' + data[i].author + ' 修订时间：' + data[i].mtime + '</p>\n' +
                    '</li>');
            }
        });
        $('#compare-content').show();
    });
    // 取消对比
    $('#compareCancel').on('click', function () {
        $('#compare-content').hide();
    });
    // 开始对比（pageOffice）
    $('#compare').on('click', function () {
        if (fileA) {
            if (oframe.ActiveDocument.Revisions.Count > 0) {
                // 前文档有修订：接受所有，并保存到服务器(保存后重新打开当前文档)，作为B与选择的文档A进行对比
                oframe.ActiveDocument.AcceptAllRevisions(); // 接受所有修订
                if (oframe.HttpInit()) {
                    oframe.HttpAddPostString("id", id);
                    oframe.HttpAddPostCurrFile("file", "");
                    var savedId = oframe.HttpPost(rootPath + '/upload');
                    alert(savedId);
                    if (savedId) {
                        POBrowser.openWindowModeless('/compare?fileA=' + fileA + '&fileB=' + savedId + '&username=' + U, 'width=1200px;height=800px;');
                        initOpen(); // 保存后重新打开当前文档
                    } else {
                        alert('保存失败');
                    }
                }
            } else {
                // 文档无修订：选择的文档作为A，当前文档作为B，直接比较
                POBrowser.openWindowModeless('/compare?fileA=' + fileA + '&fileB=' + id + '&username=' + U, 'width=1200px;height=800px;');
            }
        } else {
            alert('请选择一个版本');
        }
    });
    // 初始化，打开文档
    initOpen();
});

function initOpen() {
    if (id) {
        setTimeout(function () {
            if (id === 'new') {
                oframe.CreateNew("Word.Document");
            } else if (id === 'upload') {
                oframe.ShowDialog(1);
            } else {
                oframe.Open("./download/" + id + "?_=" + Math.random(), true, "Word.Document");
            }
        }, 333);
    } else {
        alert('未打开文档');
    }
}

function OnDocumentOpened(str, obj) {
    isOpened = true;
    oframe.ActiveDocument.Saved = true;
    oframe.ActiveDocument.TrackRevisions = true;
    oframe.ActiveDocument.ShowRevisions = true;
    oframe.ActiveDocument.ActiveWindow.View.Type = 3; //普通视图=1,大纲视图=2,页面视图=3,打印预览视图=4,主控视图=5,Web视图=6,阅读视图=7
    oframe.ActiveDocument.ActiveWindow.View.Zoom.PageFit = 2; //使页面自动适应用户的可视范围
    oframe.ActiveDocument.ActiveWindow.View.RevisionsView = 0; // 0最终 1原始
    oframe.ActiveDocument.ActiveWindow.View.ShowRevisionsAndComments = true;
    oframe.ActiveDocument.ActiveWindow.View.ShowBookmarks = true;
    oframe.ActiveDocument.ActiveWindow.View.ShowComments = true;
    oframe.ActiveDocument.ActiveWindow.View.ShowInkAnnotations = true;
    oframe.ActiveDocument.ActiveWindow.View.ShowInsertionsAndDeletions = true;
    oframe.ActiveDocument.ActiveWindow.View.RevisionsBalloonShowConnectingLines = true;

    // 找出书签
    var marks = [];
    var count = oframe.ActiveDocument.Bookmarks.Count;
    for (var i = 1; i <= count; i++) {
        var bm = oframe.ActiveDocument.Bookmarks(i);
        var mark = {name: bm.Name, start: bm.Start, end: bm.End};
        // var mark = {name: bm.Name, start: bm.Start, end: bm.End, content: oframe.ActiveDocument.Range(bm.Range.Start, bm.Range.End).Text};
        marks.push(mark);
        // console.log(JSON.stringify(mark));
    }
    // 排序，添加到界面
    marks.sort(function (a, b) {
        return a.start - b.start;
    });
    for (var i = 0; i < marks.length; i++) {
        var mark = marks[i];
        var newChild = document.createElement("p");
        // var newChild = document.createElement("label");
        var newText = document.createTextNode(mark.name);
        // newChild.setAttribute('for', 'modal_1');
        // newChild.setAttribute('onclick', 'setMarkInput("'+mark.name+'","'+ mark.content+'")');
        newChild.setAttribute('onclick', 'setMark("' + mark.name + '")');
        // newChild.setAttribute('onclick', 'setMark("'+mark.name+'","'+ mark.content+'")');
        newChild.appendChild(newText);
        document.getElementById('marks').appendChild(newChild);
    }
}

function OnDocumentClosed() {
    isOpened = false;
}

// 切换修订气球
function switchBall() {
    if (oframe.ActiveDocument.ActiveWindow.View.RevisionsBalloonSide == 1) {
        oframe.ActiveDocument.ActiveWindow.View.RevisionsBalloonSide = 0
    } else {
        oframe.ActiveDocument.ActiveWindow.View.RevisionsBalloonSide = 1
    }
}

// 点击定位到书签
function goMark(name) {
    oframe.ActiveDocument.Bookmarks(name).Select();
}

// 弹窗赋值
function setMark(name) {
    goMark(name);
    var value = prompt('请输入“' + name + '”的值：', oframe.GetFieldValue(name, ""));
    if (value != null) {
        oframe.SetFieldValue(name, value, "");
    }
}

// 给书签赋值
function setMarkVal(name, value) {
    oframe.SetFieldValue(name, value, "");
}

// 解锁限制区域
function unlock() {
    var value = prompt('请输入解锁模板密码：');
    if (value == null) {
        return;
    }
    try {
        oframe.ActiveDocument.UnProtect(value);
    } catch (e) {
        alert(e.message);
    }
    setTimeout(function () {
        oframe.ActiveDocument.TrackRevisions = true;
    }, 333)
}

function getQueryVariable(key) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] === key) {
            return pair[1];
        }
    }
    return '';
}

function selectFile() {
    var radios = document.getElementsByName("files");
    var value = 0;
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked == true) {
            value = radios[i].value;
            break;
        }
    }
    console.log('选择器：' + (value == '0'));
    if (value == '0') {
        document.getElementById('history-file').setAttribute('style', 'display:block');
        document.getElementById('local-file').setAttribute('style', 'display:none');
    } else {
        document.getElementById('history-file').setAttribute('style', 'display:none');
        document.getElementById('local-file').setAttribute('style', 'display:block');
    }
}

function updateRecord() {
    document.getElementById('update-content').setAttribute('style', 'display:block');
    // 总数
    var count = oframe.ActiveDocument.Revisions.Count;
    var revisions = [];
    // 切换到原始视图，遍历出删除的内容
    ShowCompareBefore();
    for (var i = 1; i <= count; i++) {
        var r = oframe.ActiveDocument.Revisions(i);
        if (r.Type == 2) {
            var text = oframe.ActiveDocument.Range(r.Range.Start, r.Range.End).Text.replace(/\s*/g, "");
            revisions.push({
                author: r.Author,
                type: r.Type,
                text: text,
                date: Date.parse(r.Date),
                index: r.Index,
                start: r.Range.Start,
                end: r.Range.End
            });
        }
    }
    // 切换到结果视图，遍历出增加的内容
    ShowCompareResult();
    for (var i = 1; i <= count; i++) {
        var r = oframe.ActiveDocument.Revisions(i);
        if (r.Type == 1) {
            var text = oframe.ActiveDocument.Range(r.Range.Start, r.Range.End).Text.replace(/\s*/g, "");
            revisions.push({
                author: r.Author,
                type: r.Type,
                text: text,
                date: Date.parse(r.Date),
                index: r.Index,
                start: r.Range.Start,
                end: r.Range.End
            });
        }
    }
    // 把结果画到界面
    $('.up-detail').eq(0).empty();
    $('.up-detail').eq(1).empty();
    for (var i = 0; i < revisions.length; i++) {
        console.log(JSON.stringify(revisions[i]));
        if (revisions[i].text != '') {
            if (revisions[i].author == '交通银行') {
                if (revisions[i].type == 1)
                    $('.up-detail').eq(0).append('<div class="detail-li"><span class="operate add">增加了</span><span>' + revisions[i].text + '</span></div>');
                else
                    $('.up-detail').eq(0).append('<div class="detail-li"><span class="operate add">删除了</span><span>' + revisions[i].text + '</span></div>');
            } else {
                if (revisions[i].type == 1)
                    $('.up-detail').eq(1).append('<div class="detail-li"><span class="operate add">增加了</span><span>' + revisions[i].text + '</span></div>');
                else
                    $('.up-detail').eq(1).append('<div class="detail-li"><span class="operate add">删除了</span><span>' + revisions[i].text + '</span></div>');
            }
        }
    }
}

function updateCancel() {
    document.getElementById('update-content').setAttribute('style', 'display:none');
}

function selectVersion(obj) {
    document.getElementsByClassName('up-li selected')[0].className = 'up-li';
    obj.className = 'up-li selected';
    document.getElementsByClassName('up-detail selected')[0].className = 'up-detail';
    document.getElementsByClassName('up-detail')[1].className = 'up-detail selected';
}

function checkLabel() {
    document.getElementById('check-label-content').setAttribute('style', 'display:block');
    // 找出书签
    var marks = [];
    var count = oframe.ActiveDocument.Bookmarks.Count;
    for (var i = 1; i <= count; i++) {
        var bm = oframe.ActiveDocument.Bookmarks(i);
        var mark = {name: bm.Name, start: bm.Start, end: bm.End};
        marks.push(mark);
    }
    // 排序，添加到界面
    marks.sort(function (a, b) {
        return a.start - b.start;
    });
    var tempString = '';
    for (var i = 0; i < marks.length; i++) {
        var mark = marks[i];
        tempString = tempString + '<div class="label-detail"><p class="label1">' + mark.name + '：</p><p class="label2">' + oframe.GetFieldValue(mark.name, "") + '</p></div>'
    }
    document.getElementById('label-middle').innerHTML = tempString;
}

function labelCancel() {
    document.getElementById('check-label-content').setAttribute('style', 'display:none');
}

function ShowCompareBefore() {
    oframe.ActiveDocument.ActiveWindow.View.ShowRevisionsAndComments = false;
    oframe.ActiveDocument.ActiveWindow.View.RevisionsView = 1; // 0最终 1原始
}

function ShowCompareLast() {
    oframe.ActiveDocument.ActiveWindow.View.ShowRevisionsAndComments = false;
    oframe.ActiveDocument.ActiveWindow.View.RevisionsView = 0; // 0最终 1原始
}

function ShowCompareResult() {
    oframe.ActiveDocument.ActiveWindow.View.ShowRevisionsAndComments = true;
    oframe.ActiveDocument.ActiveWindow.View.RevisionsView = 0; // 0最终 1原始
}
